package com.yricky.indesk.a.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import com.yricky.indesk.utils.PkgEvent
import com.yricky.indesk.utils.cfgChannel
import com.yricky.indesk.utils.pkgChannel


/**
 * @author Yricky
 * @date 2021/12/27
 */
class PkgEventReceiver :BroadcastReceiver() {
    fun init(context: Context){
        val intentFilter = IntentFilter()
        intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED)
        intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED)
        intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED)
        intentFilter.addDataScheme("package")
        context.registerReceiver(this, intentFilter)
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        /**
         * 获取（安装/替换/卸载）应用的 信息
         */
        /**
         * 获取（安装/替换/卸载）应用的 信息
         */
        val packages = intent?.dataString?.split(":")?.toTypedArray()?.get(1) ?: return

        when(intent.action) {
            Intent.ACTION_PACKAGE_ADDED -> {
                pkgChannel.post(PkgEvent.PkgInstalled(packages))
            }
            Intent.ACTION_PACKAGE_REMOVED -> {
                pkgChannel.post(PkgEvent.PkgUninstalled(packages))
            }
            Intent.ACTION_PACKAGE_REPLACED -> {
            }
        }
    }
}